//
//  ZZLeaveMessageController.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/7.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZLeaveMessageController.h"
#import "ZZKeyboardView.h"
#import "MyButton.h"

#import "ZZLeaveDetailCell.h"
#define cellIdentifier @"ZZLeaveDetailCell"

#import "ReportView.h"


@interface ZZLeaveMessageController ()<ZZTopicCellDelegate,UIGestureRecognizerDelegate>

@property(nonatomic,assign) int page;

@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  UITableView *listTable;
@property(nonatomic,strong)  ZZKeyboardView *keyboardView;
@end

@implementation ZZLeaveMessageController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSLog(@"-----123--------");
    
    
    self.navigationItem.title = @"留言";

    [self setNavigationBar];

    self.navigationController.navigationBarHidden = NO;

    [self.view setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    
    [self createTableView];
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self loadBegin];

    _keyboardView = [[ZZKeyboardView alloc] initWithDelegate:self changeView:_listTable show:NO style:ZZKeyboardControlsDefault];
//    _keyboardView.chatpterModel = _entity;
    __weak ZZLeaveMessageController *saveSelf = self;
    [_keyboardView setResultBlock:^(int code,NSString *text,id replayModel){
        if(code == 0){
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            [dict setObject:convertToString([UserUtil getUser].user_id) forKey:@"session_uid"];
            [dict setObject:convertToString(_user_id) forKey:@"user_id"];
            [dict setObject:convertToString(text) forKey:@"message"];
            if(replayModel!=nil){
                ZZLeaveEntity *tempModel = replayModel;
                [dict setObject:convertToString(tempModel.n_id) forKey:@"quote_id"];
                
            }else{
                [dict setObject:@"0" forKey:@"quote_id"];
            }
            [NetworkUtil POST:API_AddWall parameters:dict success:^(id responseObject, NSDictionary *dict) {
                ZZLeaveEntity *addModel = [[ZZLeaveEntity alloc] initWithDictionary:dict[@"data"]];
                addModel.user_info = [UserUtil getUser];
                [saveSelf.listArray insertObject:addModel atIndex:0];
                
                [saveSelf.listTable reloadData];
            } failure:^(NSError *error, NSString *message) {
                [PopUtil showMessage:message];
            }];
        }
    }];
    
    
    UITapGestureRecognizer *oneTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pageClick:)];
    oneTap.delegate = self;
    oneTap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:oneTap];
    
    
    
}


-(void)pageClick:(UITapGestureRecognizer *) tap{
    [_keyboardView hideKeyboard];
}



-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier];
    _listTable.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    [_listTable setFrame:CGRectMake(0, 0, ScreenWidth, self.view.bounds.size.height - 44)];
    
    [_listTable setBackgroundColor:UIColor.clearColor];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    [_listTable setSeparatorColor:LINE_COLOR];
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    
    [self setTableSeparatorInset];
    
    
    MJRefreshBackStateFooter *footer = [MJRefreshBackStateFooter  footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    _listTable.footer = footer;
    [self setTableSeparatorInset];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadBegin];
    }];
    _listTable.header = header;
}

-(void)loadBegin{
    _page = 1;
    [self loadMoreData];
}

/**
 加载更多
 */
-(void)loadMoreData{
    NSDictionary *params = @{@"session_uid":convertToString([UserUtil getUser].user_id),
                             @"user_id":convertToString(_user_id),
                             @"page_size":@"30",
                             @"page":convertIntToString(_page)
                             };
    [NetworkUtil POST:API_Mywalllist parameters:params success:^(id responseObject, NSDictionary *dict) {
        NSArray *arr = dict[@"data"][@"list"];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([_listTable.header isRefreshing]){
            [_listTable.header endRefreshing];
        }
        if([_listTable.footer isRefreshing]){
            [_listTable.footer endRefreshing];
        }
        if(self.page == 1){
            [self.listArray removeAllObjects];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
               if(_replayModel){
                    [_keyboardView setReplyModel:_replayModel];
                }
            });
        }
        for (NSDictionary *item in arr) {
            [self->_listArray addObject:[[ZZLeaveEntity alloc] initWithDictionary:item]];
        }
        
        self.page = [dict[@"data"][@"page"] intValue]+1;
        
        [self.listTable reloadData];
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([_listTable.header isRefreshing]){
            [_listTable.header endRefreshing];
        }
        if([_listTable.footer isRefreshing]){
            [_listTable.footer endRefreshing];
        }
        
//        [PopUtil showMessage:message];
    }];
}

 -(void)onCellItemClick:(ZZTopicCellClickType)type obj:(id)senderObj{
     if(type == ZZClickOpenVC){
         [self openPushVC:senderObj];
     }else{
         
         if (![UserUtil getUser].isOnline){
             [[ZZCoreTools getCoreTools] showLogin:self];
             return;
         }
         
         ZZLeaveEntity *obj = senderObj;
         NSString *top = @"置顶";
         if([obj.is_top boolValue]){
             top = @"取消置顶";
         }
         [[AlertUtil shareInstance] showSheet:nil message:nil cancelTitle:@"取消" viewController:self confirm:^(NSInteger buttonTag) {
             if(buttonTag == 0){
                 NSString *is_top = obj.is_top;
                 if([is_top boolValue]){
                     is_top = @"0";
                 }else{
                     is_top = @"1";
                 }
                 
                 [NetworkUtil POST:API_updatewalltop parameters:@{@"session_uid":[UserUtil getUser].user_id,
                                                                  @"wall_id":obj.n_id,
                                                                  @"is_top":is_top
                                                                  } success:^(id responseObject, NSDictionary *dict) {
                     [self loadBegin];
                 } failure:^(NSError *error, NSString *message) {
                     [PopUtil showMessage:message];
                 }];
             }
             if(buttonTag == 1){
                 [NetworkUtil POST:API_delWall parameters:
                    @{@"session_uid":[UserUtil getUser].user_id, @"id":obj.n_id}
                success:^(id responseObject, NSDictionary *dict) {
                        [_listArray removeObject:obj];
                        [_listTable reloadData];
                 } failure:^(NSError *error, NSString *message) {
                     [PopUtil showMessage:message];
                 }];
             }
             if(buttonTag == 2){
                 UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                 pasteboard.string = convertToString(obj.message);
                 
                 [PopUtil showMessage:@"已复制到剪切板"];
             }
             if(buttonTag == 3){
                 ReportView *report = [[ReportView alloc] initWithShareType:self];
                 report.mapping_id = obj.n_id;
                 report.mapping_uid = obj.user_info.user_id;
                 report.report_type = @"thread";
                 [report show];
             }
         } buttonTitles:top,@"删除",@"复制",@"举报", nil];
     }
 }

#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(_listArray.count > 0 ){
        ZZLeaveEntity *fist = [_listArray firstObject];
        if([fist.is_top boolValue]){
            return 44.0f;
        }
    }
    return 0.1f;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    [headerView setBackgroundColor:UIColor.whiteColor];
    if(_listArray.count > 0 ){
        ZZLeaveEntity *fist = [_listArray firstObject];
        if([fist.is_top boolValue]){
            [headerView setFrame:CGRectMake(0, 0, ScreenWidth, 44)];

            UILabel *labe = [self createLabel];
            [labe setFrame:CGRectMake(20, 10, ScreenWidth - 40, 34)];
            [labe setText:@"置顶"];
            [headerView addSubview:labe];
        }
    }
    
    return headerView;
}

// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZLeaveDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZLeaveDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] ;
    }
    cell.delegate = self;
    [cell dataToView:_listArray[indexPath.row]];
    
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //    VipModel *model=[_listArray objectAtIndex:indexPath.row];
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.row+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.listTable)
    {
        CGFloat sectionHeaderHeight = 44;
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
